package com.xukehong.demo.config;

import com.xukehong.demo.entity.User;
import com.xukehong.demo.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @Author: xkh
 * @Date: 2019/12/11 11:35
 * @Version 1.0
 */
@Service
public class MyUserService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //从数据库根据用户名获取用户信息
        System.out.println(s);
        User user = new User();
        user.setUsername(s);
        User userByName = userMapper.selectOne(user);
        UserDetails userDetails = null;
        if (userByName != null) {
            System.out.println(userByName.getPassword());
            //创建一个集合来存放权限
            Collection<GrantedAuthority> authorities = getAuthorities(user);
            //实例化UserDetails对象
            userDetails = new org.springframework.security.core.userdetails.User(s, userByName.getPassword(), true, true, true, true, authorities);
        } else {
            throw new UsernameNotFoundException("用户不存在");
        }
        return userDetails;
    }

    private Collection<GrantedAuthority> getAuthorities(User user) {
        List<GrantedAuthority> authList = new ArrayList<>();
        //每个权限前面都要加ROLE_
        authList.add(new SimpleGrantedAuthority("ROLE_" + ""));
        return authList;
    }


}
